# coding=utf-8
import json
import pandas as pd
from configs import logger


def hand_file(data):
    print(data)
    with open('../temp.txt', 'w', encoding='utf-8') as f:
        f.write(json.dumps(data, ensure_ascii=False))
    result = []
    for item in data:
        try:
            result.append(get_item(item))
        except Exception as e:
            logger.exception(e)
            print(item)
    create_csv(result)


def get_item(data):
    dd = data[0]
    result = dd.split('```\n')[0].replace('```json', '').replace('\n', '').replace(' ', '').replace('```', '')
    j_data = json.loads(result)
    j_data['合同编号'] = data[1]
    return j_data


def hand_dict(data, result=[]):
    for item in data:
        v = data[item]
        if isinstance(v, dict):
            hand_dict(v, result=result)
        else:
            temp = '%s:%s' % (item, v)
            result.append(temp)


def create_csv(result):
    df = pd.DataFrame(result)

    def hand_cell(x):
        try:
            if isinstance(x, dict):
                result = []
                hand_dict(x, result)
                print(result)
                return '\n'.join(result)
        except:
            pass
        return x

    df1 = df.applymap(hand_cell)
    df1.to_csv('ttt3.csv', index=False, sep=',')
    print('处理完成')


if __name__ == '__main__':
    with open('../temp.txt', 'r', encoding='utf-8') as f:
        data = json.load(f)
        # print(data)
        hand_file(data)
